<?php
/**
 * 跳转计费程序
 */
include(__DIR__ . '/ck/global.php');

/*
 *$dao = array(
 *    'u' => '站长编号',
 *    'w' => '屏幕宽度',
 *    'h' => '屏幕高度',
 *    'c' => '颜色位数',
 *    'f' => '浏览器中flash版本号',
 *    'l' => '投放当前js的页面地址,必有参数',
 *    't' => '投放页面的title',
 *    'r' => '来路地址,其他意义参见m参数说明',
 *    'j' => '参见m参数说明',
 *    's' => '当前浏览器会话中历史记录数量',
 *    'm' => '嵌入广告代码的方式,1 表示广告代码投放在当前页面，2表示同域用iframe嵌入，3表示不同域用iframe嵌入',
 *    'z' => '广告位编号,必有参数',
 *    'b' => '广告展示时的时间戳',
 *    'e' => '网站编号',
 *    'a' => '广告编号',
 *    'x' => '鼠标在广告素材上的移动轨迹',
 *    'y' => '鼠标点击广告时的坐标',
 *    'o' => '表示被点击的对象(如链接文字或图片)',
 *    'p' => '访问者IP',
 *    'k' => '访问者的浏览器信息',
 *    'd' => '计费信息入队列的时间,此时间也可表示为点击发生的时间',
 *);
 */

$d      = $_GET;
$time   = empty($d['time']) ? '' : $d['time'];
$sign   = empty($d['sign']) ? '' : trim($d['sign']);
$zoneId = empty($d['id'])   ? 0  : (int)$d['id'];
$isDirectToAderUrl = 0; //是否直接跳转到广告主网站

/**
 * 无签名
 * 签名无效
 * 链接超时(global.php COST_URL_LIFE = 10秒)
 * 以上情况直接跳转到广告主网站
 */
if (empty($sign)) {
    $isDirectToAderUrl = 1;
}

if ($sign != get_to_g_sign($time)) {
    $isDirectToAderUrl = 1;
}

if (time() - $time > COST_URL_LIFE) {
    $isDirectToAderUrl = 1;
}

if (empty($zoneId)) {
    exit('e1');
}

if (!$zoneRecord = Zone::getById($zoneId)) {
    exit('e2');
}

if (empty($zoneRecord['ids'])) {
    exit('e3');
}

$tmp = array_shift($zoneRecord['ids']);

if (empty($tmp['ad_id'])) {
    exit('e4');
}

if (!$adRecord = Ad::getById($tmp['ad_id'])) {
    exit('e5');
}

$uid = $zoneRecord['uid'];

if (!$siteRecords = Site::getByUid($uid)) {
    exit('e6');
}

if (!$site = array_shift($siteRecords)) {
    exit('e7');
}

$dao = [    
    'u' => $uid,
    'w' => (empty($d['w']) ? '1' : $d['w']),
    'h' => (empty($d['h']) ? '1' : $d['h']),
    'c' => (empty($d['c']) ? '1' : $d['c']),
    'f' => '',
    'l' => $site['domain'],
    't' => '',
    'r' => $_SERVER["HTTP_REFERER"],
    'j' => '1',
    's' => '0',
    'm' => '1',
    'z' => $zoneId,
    'b' => $time,
    'e' => $site['id'],
    'a' => $adRecord['id'],
    'x' => '0',
    'y' => '0',
    'o' => 'z',
    'p' => getClientIp(),
    'k' => $_SERVER['HTTP_USER_AGENT'],
    'd' => time(),
];

$url = '';

if ($device = PlanDevice::detect($_SERVER['HTTP_USER_AGENT'])) {
    $urlKey = 'url_' . $device;
    $url    = empty($adRecord[$urlKey]) ? '' : $adRecord[$urlKey];
}

if (empty($url)) {
    exit('e8');
}

ClickStream::add($dao);
header('location:' . $url);
